declare namespace pm = "http://www.politicalmashup.nl";
declare namespace t = "http://www.somewebsite.be/topics";
declare namespace s = "http://www.somewebsite.be/speakers";

let $members := collection('/db/projdb/ge-2009')/root/pm:proceedings/pm:topic/pm:stage-direction/pm:members/pm:person

let $speakers := distinct-values( 
    for $m in $members
        return data($m/@pm:speaker)
)

let $unsortedTopics := collection('/db/projdb/ge-2009')/root/pm:proceedings/pm:topic

let $topics :=
    for $topic in $unsortedTopics
        where ( not(starts-with(data($topic/@pm:title),"Stemming nr.")) 
            and not(starts-with(data($topic/@pm:title),"BIJLAGEN"))
            and not(starts-with(data($topic/@pm:title),"OPENING VAN DE VERGADERING"))
            and not(starts-with(data($topic/@pm:title), "MEDEDELING VAN DE VOORZITTER"))
            and not(starts-with(data($topic/@pm:title), "INGEKOMEN STUKKEN EN MEDEDELINGEN"))
            and not(starts-with(data($topic/@pm:title), "SAMENSTELLING VAN DE COMMISSIES")) 
            and not(starts-with(data($topic/@pm:title), "VERONTSCHULDIGINGEN"))
            and not(starts-with(data($topic/@pm:title), "OPENING VAN DE ZITTING"))
            and not(starts-with(data($topic/@pm:title), "REGELING VAN DE WERKZAAMHEDEN"))
            and not(starts-with(data($topic/@pm:title), "BOODSCHAPPEN"))
            and not(starts-with(data($topic/@pm:title), "TOESPRAAK VAN DE VOORZITTER")) )
        return $topic

let $result := element result {

    element t:topics {
        for $topic in $topics
            return element t:topic {
                element t:id {
                    data($topic/@pm:id)
                },
                element t:title {
                    data($topic/@pm:title)
                },
                element t:content{
                    let $p := $topic/pm:speech[data(@pm:role) != "chair"]/pm:p
                    for $j in $p
                        return data($j)
                }
            }
    },
    
    element s:speakers {
        for $speaker in $speakers
            return element s:speaker{
                element s:name{
                    data($speaker)
                },                
                element s:topics {
                    for $topic in $topics where ( data($topic/pm:speech/@pm:speaker) = data($speaker) )
                        return element s:id{
                            data($topic/@pm:id)
                        }
                }
            }
    }
}


let $collection := 'xmldb:exist:///db/projdb'
let $file-name := 'input-data-for-clustering.xml'
let $store-return-status := xmldb:store($collection, $file-name, $result )

return <message>New Document Created {$store-return-status} at {$collection}/{$file-name}</message>